package leetcode

//https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
fun main(args: Array<String>) {

//    for (i in 9 downTo 0) println(i)
    println(removeDuplicates2(intArrayOf(1,1)))
}

fun removeDuplicates(nums: IntArray): Int {
    if (nums.size == 1) return 1

    var result = nums.size
    var v = 1

    val end = nums.size - 1
    for (i in end downTo 1) {

        if (nums[i - 1] == nums[i]) {
            v++
            if (v == 3) {
                result--
                v--
                //place
                nums[i]
            }
        } else {
            v = 1
        }

    }
    return result
}

fun removeDuplicates2(nums: IntArray): Int {

    if (nums.size < 3) return nums.size

    var result = 0

    var v = 1
    var i = 1
    while (i <= nums.size - 1 - result) {
        if (nums[i - 1] == nums[i]) {
            v++
            if (v == 3) {
                v--
                result++
                switchAfter(i , nums)
                continue  //继续i位置的新值和前面的数比较 ，否则会遗漏i位置的新值仍然与之前数字相同的情况
            }
        } else {
            v = 1
        }

        i++
    }

    nums.forEach { print("$it\t") }
    println()
    return nums.size - result
}

fun switchAfter(i: Int, nums: IntArray) {
    var j = i
    while (j < nums.size - 1) {
        val t = nums[j]
        nums[j] = nums[j + 1]
        nums[j + 1] = t
        j++
    }
}
